﻿using System;
using System.Data;
using System.Globalization;
using System.Web.UI.WebControls;
using Pantry.Business;
using Pantry.Commons;
using Pantry.Entity;

namespace Pantry.Web.Users
{
    public partial class OrganizationDetails : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            ListTypeOfBusiness.SendvaluesToThePage += delegate(string message)
            {
                string[] str = message.Split('$');
                TextBoxTypeOfBusiness.Text = str[0];
                TextBoxSicCode.Text = str[1];
                HiddenFieldTypeOfBusinessId.Value = str[2];
            };
            ListContact.SendvaluesToThePage += delegate(string contact)
            {
                string[] contacts = contact.Split('$');
                HiddenFieldContactId.Value = contacts[0];
                TextBoxLeadContact.Text = contacts[1];
            };
            ListPostcode.sendPostcodeToPage += delegate(string values)
            {
                string[] postcodeValues = values.Split('$');
                TextBoxPostcode.Text = postcodeValues[0];
                TextBoxTown.Text = postcodeValues[1];
                TextBoxCounty.Text = postcodeValues[2];
                DropDownListNational.SelectedValue = postcodeValues[3];
            };
            ListAddress.SendvaluesToThePage += delegate(string address)
            {
                string[] addresses = address.Split('$');
                HiddenFieldAddressId.Value = addresses[0];
                TextBoxPostcode.Text = addresses[1];

            };

            if (!IsPostBack)
            {
                if (Request.QueryString["action"] == "create")
                {
                    LoadDataDropDownList();
                }
                else if (Request.QueryString["action"] == "update" && Request.QueryString["id"] != null)
                {
                    try
                    {
                        LoadDataDropDownList();
                        var organizationId = int.Parse(Request.QueryString["id"]);
                        LoadEditData(organizationId);
                    }
                    catch (FormatException ex)
                    {
                        ExceptionHandler.WriteErrorLog(ex);
                    }
                }
            }
            if (Request.QueryString["id"] == null)
            {
                ButtonInActive.Visible = false;
            }
        }
        private void LoadDataDropDownList()
        {
            //Country
            var dt = new CountryBus().SelectAllCountry();
            DropDownListNational.DataSource = dt;
            DropDownListNational.DataValueField = "CountryId";
            DropDownListNational.DataTextField = "CountryName";
            DropDownListNational.DataBind();
            //GovOfficeRegion
            var dt2 = new GovOfficeRegionBus().SelectAllGovOfficeRegion();
            DropDownListGovOfficeRegion.DataSource = dt2;
            DropDownListGovOfficeRegion.DataValueField = "GovOfficeRegionId";
            DropDownListGovOfficeRegion.DataTextField = "GovOfficeRegionName";
            DropDownListGovOfficeRegion.DataBind();
            //TrustDistrict
            var dt3 = new TrustDistrictBus().SelectAll();
            DropDownListTrustDistrict.DataSource = dt3;
            DropDownListTrustDistrict.DataValueField = "TrustDistrictId";
            DropDownListTrustDistrict.DataTextField = "TrustDistrictName";
            DropDownListTrustDistrict.DataBind();
            //TrustRegion
            var dt4 = new TrustRegionBus().SelectAll();
            DropDownListTrustRegion.DataSource = dt4;
            DropDownListTrustRegion.DataValueField = "TrustRegionId";
            DropDownListTrustRegion.DataTextField = "TrustRegionName";
            DropDownListTrustRegion.DataBind();
            //EOI Service 
            var dt13 = new ServiceOrgBus().Select(127);
            CheckBoxListEOIService.DataSource = dt13;
            CheckBoxListEOIService.DataValueField = "ServiceID";
            CheckBoxListEOIService.DataTextField = "ServiceName";
            CheckBoxListEOIService.DataBind();
            //EOI Programmes
            var dt5 = new ServiceOrgBus().Select(126);
            CheckBoxListEOIProgrammes.DataSource = dt5;
            CheckBoxListEOIProgrammes.DataValueField = "ServiceID";
            CheckBoxListEOIProgrammes.DataTextField = "ServiceName";
            CheckBoxListEOIProgrammes.DataBind();
            // Organnisation Specialism
            var dt6 = new ServiceOrgBus().Select(7);
            CheckBoxListOrgannisationSpecialism.DataSource = dt6;
            CheckBoxListOrgannisationSpecialism.DataValueField = "ServiceID";
            CheckBoxListOrgannisationSpecialism.DataTextField = "ServiceName";
            CheckBoxListOrgannisationSpecialism.DataBind();
            // Service Disabilities Capabilities
            var dt7 = new ServiceOrgBus().Select(1);
            CheckBoxListServiceDisabilitiesCapabilities.DataSource = dt7;
            CheckBoxListServiceDisabilitiesCapabilities.DataValueField = "ServiceID";
            CheckBoxListServiceDisabilitiesCapabilities.DataTextField = "ServiceName";
            CheckBoxListServiceDisabilitiesCapabilities.DataBind();
            // Service Barriers Capabilities
            var dt8 = new ServiceOrgBus().Select(2);
            CheckBoxListServiceBarriersCapabilities.DataSource = dt8;
            CheckBoxListServiceBarriersCapabilities.DataValueField = "ServiceID";
            CheckBoxListServiceBarriersCapabilities.DataTextField = "ServiceName";
            CheckBoxListServiceBarriersCapabilities.DataBind();
            // Service Benifits Capabilities
            var dt9 = new ServiceOrgBus().Select(3);
            CheckBoxListServiceBenifitsCapabilities.DataSource = dt9;
            CheckBoxListServiceBenifitsCapabilities.DataValueField = "ServiceID";
            CheckBoxListServiceBenifitsCapabilities.DataTextField = "ServiceName";
            CheckBoxListServiceBenifitsCapabilities.DataBind();
            // Service Personal Cirumstances Capabilities
            var dt10 = new ServiceOrgBus().Select(4);
            CheckBoxListServicePersonalCirumstancesCapabilities.DataSource = dt10;
            CheckBoxListServicePersonalCirumstancesCapabilities.DataValueField = "ServiceID";
            CheckBoxListServicePersonalCirumstancesCapabilities.DataTextField = "ServiceName";
            CheckBoxListServicePersonalCirumstancesCapabilities.DataBind();
            // Service Ethnicity Capabilities
            var dt11 = new ServiceOrgBus().Select(5);
            CheckBoxListServiceEthnicityCapabilities.DataSource = dt11;
            CheckBoxListServiceEthnicityCapabilities.DataValueField = "ServiceID";
            CheckBoxListServiceEthnicityCapabilities.DataTextField = "ServiceName";
            CheckBoxListServiceEthnicityCapabilities.DataBind();
            // Accreditation
            var dt12 = new ServiceOrgBus().Select(6);
            CheckBoxListAccreditation.DataSource = dt12;
            CheckBoxListAccreditation.DataValueField = "ServiceID";
            CheckBoxListAccreditation.DataTextField = "ServiceName";
            CheckBoxListAccreditation.DataBind();
        }
        private void LoadEditData(int organizationId)
        {
            var organization = new OrganizationBus().ReturnOrganizationById(organizationId);
            TextBoxOrgannisationName.Text = organization.Name;
            HiddenFieldName.Value = organization.Name;
            TextBoxOrgannisationShortDescription.Text = organization.ShortDescription;
            HiddenFieldContactId.Value = organization.ContactId.ToString(CultureInfo.CurrentCulture);
            TextBoxLeadContact.Text = new ContactBus().ContactObjectById(organization.ContactId).FirstName + ' ' +
                                      new ContactBus().ContactObjectById(organization.ContactId).Surname;
            TextBoxAddress1.Text = organization.Address1;
            TextBoxAddress2.Text = organization.Address2;
            TextBoxAddress3.Text = organization.Address3;
            TextBoxPostcode.Text = organization.Postcode;
            TextBoxTown.Text = organization.City;
            TextBoxCounty.Text = organization.County;
            DropDownListNational.SelectedValue = organization.Country;
            CheckBoxExpression.Checked = organization.ExpOfInterest;
            CheckBoxPreferred.Checked = organization.PreferredOrg;
            HiddenFieldTypeOfBusinessId.Value = organization.TypeOfBusinessId.ToString(CultureInfo.CurrentCulture);
            TextBoxTypeOfBusiness.Text = new TypeOfBusinessBus().TypeOfBusinessById(organization.TypeOfBusinessId).Rows[0]["TypeName"].ToString();
            TextBoxSicCode.Text = new TypeOfBusinessBus().TypeOfBusinessById(organization.TypeOfBusinessId).Rows[0]["SicCode"].ToString();
            TextBoxFullDescription.Text = organization.FullDescription;
            TextBoxPhoneNumber.Text = organization.PhoneNumber;
            TextBoxFax.Text = organization.Fax;
            TextBoxEmail.Text = organization.Email;
            TextBoxWebAddress.Text = organization.WebAddress;
            TextBoxCharityNumber.Text = organization.CharityNumber;
            TextBoxCompanyNumber.Text = organization.CompanyNumber;
            
            LoadEditCheckBoxData(CheckBoxListOrgannisationSpecialism, organizationId, 7);
            LoadEditCheckBoxData(CheckBoxListServiceDisabilitiesCapabilities, organizationId, 1);
            LoadEditCheckBoxData(CheckBoxListServiceBarriersCapabilities, organizationId, 2);
            LoadEditCheckBoxData(CheckBoxListServiceBenifitsCapabilities, organizationId, 3);
            LoadEditCheckBoxData(CheckBoxListServicePersonalCirumstancesCapabilities, organizationId, 4);
            LoadEditCheckBoxData(CheckBoxListServiceEthnicityCapabilities, organizationId, 5);
            LoadEditCheckBoxData(CheckBoxListAccreditation, organizationId, 6);
            LoadEditCheckBoxData(CheckBoxListEOIProgrammes, organizationId, 126);
            LoadEditCheckBoxData(CheckBoxListEOIService, organizationId, 127);

        }
        protected void ButtonSaveClick(object sender, EventArgs e)
        {
            var isExists = new OrganizationBus().CheckOrganizationNameExists(TextBoxOrgannisationName.Text.Trim());
            var organizations = new Organization
                                    {
                                        Name = TextBoxOrgannisationName.Text,
                                        ShortDescription = TextBoxOrgannisationShortDescription.Text,
                                        ContactId = Convert.ToInt32(HiddenFieldContactId.Value),
                                        Address1 = TextBoxAddress1.Text,
                                        Address2 = TextBoxAddress2.Text,
                                        Address3 = TextBoxAddress3.Text,
                                        Postcode = TextBoxPostcode.Text,
                                        City = TextBoxTown.Text,
                                        County = TextBoxCounty.Text,
                                        Country = DropDownListNational.SelectedValue,
                                        PreferredOrg = CheckBoxPreferred.Checked,
                                        ExpOfInterest = CheckBoxExpression.Checked,
                                        TypeOfBusinessId = Convert.ToInt32(HiddenFieldTypeOfBusinessId.Value),
                                        FullDescription = TextBoxFullDescription.Text,
                                        PhoneNumber = TextBoxPhoneNumber.Text,
                                        Fax = TextBoxFax.Text,
                                        Email = TextBoxEmail.Text,
                                        WebAddress = TextBoxWebAddress.Text,
                                        CharityNumber = TextBoxCharityNumber.Text,
                                        CompanyNumber = TextBoxCompanyNumber.Text,
                                        IsActive = true
                                    };

            if (DropDownListTrustRegion.SelectedValue.Length > 0)
            {
                organizations.TrustRegionId = int.Parse(DropDownListTrustRegion.SelectedValue);
            } if (DropDownListTrustDistrict.SelectedValue.Length > 0)
            {
                organizations.TrustDistrictId = int.Parse(DropDownListTrustDistrict.SelectedValue);
            } if (DropDownListGovOfficeRegion.SelectedValue.Length > 0)
            {
                organizations.GovOffRegionId = int.Parse(DropDownListGovOfficeRegion.SelectedValue);
            }
            try
            {
                if (Request.QueryString["action"] == "update" && Request.QueryString["id"] != null)
                {
                    var organizationId = int.Parse(Request.QueryString["id"]);

                    var organizationName = HiddenFieldName.Value;
                    if (organizationName != TextBoxOrgannisationName.Text)
                    {
                        if (!isExists)
                        {
                            organizations.Id = organizationId;
                            var result = new OrganizationBus().EditOrganizations(organizations);
                            if (result)
                            {
                                UpdateDataFromCheckListBox(CheckBoxListOrgannisationSpecialism, organizationId, 7);
                                UpdateDataFromCheckListBox(CheckBoxListServiceDisabilitiesCapabilities, organizationId, 1);
                                UpdateDataFromCheckListBox(CheckBoxListServiceBarriersCapabilities, organizationId, 2);
                                UpdateDataFromCheckListBox(CheckBoxListServiceBenifitsCapabilities, organizationId, 3);
                                UpdateDataFromCheckListBox(CheckBoxListServicePersonalCirumstancesCapabilities, organizationId, 4);
                                UpdateDataFromCheckListBox(CheckBoxListServiceEthnicityCapabilities, organizationId, 5);
                                UpdateDataFromCheckListBox(CheckBoxListAccreditation, organizationId, 6);
                                UpdateDataFromCheckListBox(CheckBoxListEOIProgrammes, organizationId, 126);
                                UpdateDataFromCheckListBox(CheckBoxListEOIService, organizationId, 127);

                            }
                            Page.ClientScript.RegisterStartupScript(GetType(), "MyKey",
                                                                    result
                                                                        ? "showmessage('Update Organization successfully !','SUCCESS','','false');"
                                                                        : "showmessage('Update Organization failed !','ERROR','','false');",
                                                                    true);
                        }
                        else
                        {
                            TextBoxOrgannisationName.Focus();
                            Page.ClientScript.RegisterStartupScript(GetType(), "MyKey",
                                                                    "showmessage('Organization Name is already exists !','ERROR','','false');",
                                                                    true);

                        }

                    }
                    else
                    {
                        organizations.Id = organizationId;
                        var result = new OrganizationBus().EditOrganizations(organizations);
                        if (result)
                        {
                            UpdateDataFromCheckListBox(CheckBoxListOrgannisationSpecialism, organizationId, 7);
                            UpdateDataFromCheckListBox(CheckBoxListServiceDisabilitiesCapabilities, organizationId, 1);
                            UpdateDataFromCheckListBox(CheckBoxListServiceBarriersCapabilities, organizationId, 2);
                            UpdateDataFromCheckListBox(CheckBoxListServiceBenifitsCapabilities, organizationId, 3);
                            UpdateDataFromCheckListBox(CheckBoxListServicePersonalCirumstancesCapabilities, organizationId, 4);
                            UpdateDataFromCheckListBox(CheckBoxListServiceEthnicityCapabilities, organizationId, 5);
                            UpdateDataFromCheckListBox(CheckBoxListAccreditation, organizationId, 6);
                            UpdateDataFromCheckListBox(CheckBoxListEOIProgrammes, organizationId, 126);
                            UpdateDataFromCheckListBox(CheckBoxListEOIService, organizationId, 127);
                        }
                        Page.ClientScript.RegisterStartupScript(GetType(), "MyKey",
                                                                result
                                                                    ? "showmessage('Update Organization successfully !','SUCCESS','','false');"
                                                                    : "showmessage('Update Organization failed !','ERROR','','false');",
                                                                true);
                    }
                }
                else
                {
                    if (!isExists)
                    {
                        var result = new OrganizationBus().InsertOrganizations(organizations);
                        if (result)
                        {
                            var organizationId = int.Parse(new OrganizationBus().SelectOrganizationId(organizations.Name).Rows[0]["ID"].ToString());
                            if (organizationId != 0)
                            {
                                UpdateDataFromCheckListBox(CheckBoxListOrgannisationSpecialism, organizationId, 7);
                                UpdateDataFromCheckListBox(CheckBoxListServiceDisabilitiesCapabilities, organizationId, 1);
                                UpdateDataFromCheckListBox(CheckBoxListServiceBarriersCapabilities, organizationId, 2);
                                UpdateDataFromCheckListBox(CheckBoxListServiceBenifitsCapabilities, organizationId, 3);
                                UpdateDataFromCheckListBox(CheckBoxListServicePersonalCirumstancesCapabilities, organizationId, 4);
                                UpdateDataFromCheckListBox(CheckBoxListServiceEthnicityCapabilities, organizationId, 5);
                                UpdateDataFromCheckListBox(CheckBoxListAccreditation, organizationId, 6);
                                UpdateDataFromCheckListBox(CheckBoxListEOIProgrammes, organizationId, 126);
                                UpdateDataFromCheckListBox(CheckBoxListEOIService, organizationId, 127);
                            }
                        }
                        Page.ClientScript.RegisterStartupScript(GetType(), "MyKey",
                                                                result
                                                                    ? "showmessage('Create new Organization successfully !','SUCCESS','','false');"
                                                                    : "showmessage('Cannot create new Organization !','ERROR','','false');",
                                                                true);
                    }
                    else
                    {
                        TextBoxOrgannisationName.Focus();
                        Page.ClientScript.RegisterStartupScript(GetType(), "MyKey",
                                                                "showmessage('Organization Name is already exists !','ERROR','','false');",
                                                                true);

                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionHandler.WriteErrorLog(ex);
                Response.Write(ex.Message);
            }

        }
        protected void ButtonBackClick(object sender, EventArgs e)
        {
            Response.Redirect("ViewListOrganization.aspx");
        }
        protected void ButtonInActiveClick(object sender, EventArgs e)
        {
            var organizationId = int.Parse(Request.QueryString["id"]);

            var result = new OrganizationBus().MarkActivated(false, organizationId);
            if (result)
            {
                Response.Redirect("ViewListOrganization.aspx");
            }
        }
        private static void UpdateDataFromCheckListBox(ListControl checkBoxList, int organizationId, int parentId)
        {
            var serviceOrgRelateBus = new ServiceOrgRelateBus();
            var serviceOrgRelate = new ServiceOrgRelate
                                 {
                                     OrganizationId = organizationId,
                                     ServiceParentId = parentId
                                 };
            for (var i = 0; i < checkBoxList.Items.Count; i++)
            {
                if (checkBoxList.Items[i].Selected)
                {
                    serviceOrgRelate.ServiceId = int.Parse(checkBoxList.Items[i].Value);
                    serviceOrgRelate.IsActive = true;
                    if (serviceOrgRelateBus.IsExist(serviceOrgRelate))
                    {
                        serviceOrgRelateBus.Update(serviceOrgRelate);

                    }
                    else
                    {

                        serviceOrgRelateBus.Insert(serviceOrgRelate);
                    }
                }
                else
                {
                    serviceOrgRelate.ServiceId = int.Parse(checkBoxList.Items[i].Value);
                    serviceOrgRelate.IsActive = false;
                    if (serviceOrgRelateBus.IsExist(serviceOrgRelate))
                    {
                        serviceOrgRelateBus.Update(serviceOrgRelate);

                    }
                    else
                    {

                        serviceOrgRelateBus.Insert(serviceOrgRelate);
                    }
                }

            }
        }
        private static void LoadEditCheckBoxData(ListControl checkBoxList, int organizationId, int parentId)
        {
            var listValue = new ServiceOrgRelateBus().Select(parentId, organizationId);
            foreach(DataRow dr in listValue.Rows)
            {
                foreach (ListItem  listItem in checkBoxList.Items)
                {
                    if(listItem.Value == dr["ServiceID"].ToString())
                    {
                        listItem.Selected = Boolean.Parse(dr["IsActive"].ToString());
                    }
                }
            }
        }

        protected void CheckBoxExpression_CheckedChanged(object sender, EventArgs e)
        {
            if (CheckBoxExpression.Checked)
            {
                ClientScript.RegisterStartupScript(GetType(), "MyKey", "changetab();", true);
            }
        }
        protected void LoadByServiceId()
        {
            try
            {
                var servicePremiseBus = new ServicePremiseBus();
                if (Request.QueryString["id"] != null)
                {
                    int serviceId = int.Parse(Request.QueryString["id"]);
                    DataTable listPremise = servicePremiseBus.SelectServicePremiseByServiceId(serviceId);
                    RepeaterListPremises.DataSource = listPremise;
                    RepeaterListPremises.DataBind();
                }
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }
    }
}
